<%@ page language="java" pageEncoding="UTF-8" %>
<%@include file="/WEB-INF/view/common/common.jsp" %>
<!doctype html>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="${ctx}/resources/mallcss/initcss.css" rel="stylesheet">
    <link href="${ctx}/resources/mallcss/common.css" rel="stylesheet">
    <%--<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>--%>
    <script src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
    <!--<script src="https://cdn.bootcss.com/scrollup/2.4.1/jquery.scrollUp.js"></script>-->
    <script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
    <script type="text/javascript" src="${ctx}/resources/malljs/mysocket.js"></script>
    <style>

        html, body {
            height: 100%;
        }

        .none {
            visibility: hidden;
        }

        .message {
            overflow: scroll;
            -webkit-overflow-scrolling: touch;
            background-color: #EAEBEA;
            height: 100%;
            padding-bottom: 4em;
        }

        .footer {
            position: fixed;
            bottom: 0;
            width: 100%;
        }

        .edit {
            width: 100%;
            background-color: #F2F3F2;
        }

        .footer div {
            display: inline-block;
            float: left;
        }

        .vb, .eb, .add, .wb, .send {
            width: 14%;
            text-align: center;

        }

        .vb img, .eb img, .add img, .wb img {
            width: 3.5em;
            cursor: pointer;
            /*margin: 0 auto;*/
        }

        .rb, .sb {
            width: 58%;
            height: 3.5em;

        }

        span.press {
            background-color: #E1E2E1;
        }

        .rb input {
            outline: none;
            border: none;
            border-bottom: 1px solid #D7D8D7;
            background-color: #F2F3F2;
            width: 100%;
            height: 2.1em;
            padding-top: 0.4em;
            /*padding-top: 0.2em;*/
            font-size: 1.2em;
            /*line-height: 22em;*/
        }

        .sb span {
            display: block;
            text-align: center;
            width: 100%;
            color: #818281;
            height: 2.5em;
            margin-top: 0.4em;
            line-height: 2.5em;
            border: 1px solid #DBDCDB;
        }

        .send {
            cursor: none;
        }

        .send span {
            cursor: pointer;
            background-color: #1AA818;
            color: white;
            display: block;
            width: 3em;
            height: 2.5em;
            margin-top: 0.5em;
            line-height: 2.5em;
            border-radius: 4px;
        }

        .bar {
            /*height: em;*/

            margin-top: 1em;
            overflow: hidden;
        }

        .my {
            padding-right: 0.5em;
        }

        .other {
            padding-left: 0.5em;
        }

        .bar div {
            display: inline-block;

        }

        .my div {
            float: right;
        }

        .other div {
            float: left;
        }

        .bar .img {
            height: 3em;
            width: 3em;

        }

        .my .img {
            margin-left: 1em;
        }

        .other .img {
            margin-right: 1em;
        }

        .bar .img img {
            width: 100%;
            height: 100%;
        }

        .bar .mes {
            display: inline-block;
            height: 100%;
            word-break: break-all;
            position: relative;
            line-height: 3em;
            padding: 0 10px;
            /*background-color: #FEFFFE;*/

            min-height: 3em;
            border-radius: 4px;
            max-width: calc(100% - 10em);
        }

        .bar .mes.images {
            padding: 0;
        }

        .my .mes {
            background-color: #A1E75A;
        }

        .mes.voice img {
            height: 1.8em;
            width: 1.8em;
        }

        .my .mes span {
            position: relative;
            left: -2.5em;
            color: #A9AAA9;
        }

        .other .mes span {
            position: relative;
            right: -3.5em;
            color: #A9AAA9;
        }

        .mes span.nrb {
            display: inline-block;
            width: 0.8em;
            height: 0.8em;
            background-color: red;
            border-radius: 1em;
        }

        .my .mes.voice img {
            padding-left: 1.5em;
            padding-right: 0.3em;
        }

        .other .mes {
            background-color: #FEFFFE;
        }

        .other .mes.voice img {
            padding-right: 1.5em;
            padding-left: 0.3em;
        }

        .mes.images img {
            max-width: 13em;
        }

        .mes:before {
            content: "";
            position: absolute;
            top: 0.8em;
            /*background: inherit;*/
            /*background-clip: border-box;*/
            /*background-origin: border-box;*/
            /*right: 100%;*/
            /*border-right-color: #fafafa;*/

            /*right: inherit;*/

        }

        .mes.images:before {
            background: inherit;
            /*background-size: auto;*/
            /*background-clip: border-box;*/
            /*background-origin: border-box;*/

        }

        .my .mes:before {
            left: 100%;
            border: 6px solid transparent;
            border-left-color: #A1E75A;

        }

        .my .mes.images:before {
            /*left: 100%;*/
            border: 6px solid #E9EBE9;
            border-left-color: transparent;
            background-position: -6px -0.8em;
        }

        .other .mes:before {
            right: 100%;
            border: 6px solid transparent;
            border-right-color: #FEFFFE;
        }

        .other .mes.images:before {
            /*left: 100%;*/
            border: 6px solid #E9EBE9;
            border-right-color: transparent;
            background-position: 0 -0.8em;
        }

        /*.mes :after {*/
        /*box-sizing: border-box;*/
        /*}*/

        .time {
            text-align: center;
            padding-top: 1em;
        }

        .time span {
            background-color: #D4D5D4;
            color: #FEFFFE;
            padding: 0.2em;
            font-size: 0.8em;
        }

        .blank {
            height: 3em;
        }

        .sdiv {
            display: none;
            position: fixed;
            width: 100%;
            z-index: 1000;
        }

        .speaking {
            margin: 50% auto 0;
            width: 14em;
            height: 14em;
            text-align: center;
            background-color: #686968;
            opacity: 0.9;
        }

        .speaking img:first-child {
            width: 7em;
            height: 8em;
            margin-top: 2em;
            line-height: 100%;
        }

        #simg {
            width: 3em;
            height: 7em;
            margin-top: 3em;
            line-height: 100%;
        }

        .speaking p {
            margin-top: 1em;
            color: white;
        }


    </style>
    <title>${toAgent.realName}</title>
</head>
<body style="background: rgb(232, 232, 232);">

<div class="sdiv">
    <div class="speaking">
        <img src="${ctx}/resources/mallimages/speak.png" alt="">
        <img id="simg" src="${ctx}/resources/mallimages/v1.jpg" alt="">
        <p>手指上滑,取消发送</p>
    </div>
</div>

<div class="message">




    <%--<div class="other"></div>--%>
</div>
<div class="footer">
    <div class="edit">
        <div class="vb ww">
            <img src="${ctx}/resources/mallimages/yy.png" alt="">
        </div>

        <div class="wb wv" style="display: none">
            <img src="${ctx}/resources/mallimages/wd.png" alt="">
        </div>

        <div class="sb wv" style="display: none">
            <span>按住 说话</span>
        </div>

        <div class="rb ww">
            <input type="text">
        </div>
        <div class="eb">
            <img src="${ctx}/resources/mallimages/bq.png" alt="">
        </div>
        <div class="add">
            <img src="${ctx}/resources/mallimages/add.png" alt="">
        </div>
        <div class="send" style="display: none">
            <span>发送</span>
        </div>
    </div>


</div>

<script>
    $(function () {

        if(localStorage.clear10 == null||localStorage.clear10==false){
        localStorage.clear();
            localStorage.clear10 = true;
        }

        //发送方的信息
        var mid = "${user.id}";
        var avatar = "${user.headimgurl}";
        var name = "${user.realName}";
        var code = "${user.agentCode}";

        <c:choose>
            <c:when test="${isG}">
            var oid = "G${chatGroup.id}";
            //接收方其它的信息 主要用于本地消息记录
            var oavatar = "${chatGroup.avatar}";
            var oname = "${chatGroup.name}";
            var ocode = "${chatGroup.id}";
            </c:when>

            <c:otherwise>
            var oid = "${toAgent.id}";
            //接收方其它的信息 主要用于本地消息记录
            var oavatar = "${toAgent.headimgurl}";
            var oname = "${toAgent.realName}";
            var ocode = "${toAgent.agentCode}";
            </c:otherwise>
        </c:choose>






        showMessages(oid);

        //发送消息封装
        function sendMessage(fromId, toId, avatar, msg, name, code, type) {
//            msg="http://c.hiphotos.baidu.com/image/h%3D300/sign=a497744e43ed2e73e3e9802cb703a16d/6a63f6246b600c3315a94502134c510fd8f9a12c.jpg+http://c.hiphotos.baidu.com/image/h%3D300/sign=a497744e43ed2e73e3e9802cb703a16d/6a63f6246b600c3315a94502134c510fd8f9a12c.jpg";
//            type = "img";//模拟是声音 TODO
            //简单生成id
            var msgid = fromId + new Date().getTime();
            var message = {
                "msgId": msgid,
                "fromId": fromId,
                "toId": toId,
                "avatar": avatar,
                "oavatar":oavatar,
                "oname":oname,
                "ocode":ocode,
                "msg": msg,
                "name": name,
                "code": code,
                "type": type
            }
            sockjs.send(JSON.stringify(message));//发送
            return message;
        }



        $(".wb").click(function () {
            $(".ww").show();
            $(".wv").hide();
        });

        $(".vb").click(function () {
            $(".ww").hide();
            $(".wv").show();
        })

        $(".rb>input").keyup(function () {
            var value = $(this).val();
            if (value != null && value != "") {
                $(".add").hide();
                $(".send").show();
            } else {
                $(".send").hide();
                $(".add").show();
            }
        })

        $(".send").click(function () {
            var content = $("input").val();
            $("input").val("");
            $("input").keyup();
            var msg = sendMessage(mid, oid, avatar, content, name, code, "text");//socket发送
            showMessage(msg);
//            $("#mt").tmpl(msg).appendTo($(".message"));//实时显示
            saveMsg(msg, oid);//存储数据
//            if ($(".message")[0].scrollHeight > $(window).height()) {
//                $('.message').animate({scrollTop: $(".message")[0].scrollHeight}, 200);
//            }
//
//            setTimeout(function () {
//                autoReplay(content);
//            }, 1000);
        })

//
//        //存储数据
//        var saveMsg = function (msg, key) {
//            var array = localStorage.getItem(key);
//            if (array == null) {
//                array = [];
//            } else {
//                array = JSON.parse(array);
//            }
//            array.push(msg);
//            localStorage.setItem(key, JSON.stringify(array));
//            console.log(msg + "保存成功" + (JSON.stringify(array)));
//        }


//        //删除聊天记录
//        var removeMessage = function (key, id) {
//            if (key < 0) {//清除所有
//                localStorage.clear();
//            } else {
//                if (id < 0) {//清楚当前聊天的所有
//                    localStorage.removeItem(key);
//                } else {
//                    var msgs = loadMessage(key);
//                    for (var msg in msgs) {
//                        if (msg.id == id) {
//                            msgs.splice(msg);
//                        }
//                    }
//                }
//            }
//
//        }

        //回车键监听
        $("input").keydown(function (e) {
            if (e.keyCode == 13) {
                $(".send").click();
            }
        })


        //渲染聊天记录
        function showMessages(key) {
            try {
                var messages = getMsgsArrayByUid(key);
                $(".message").css("opacity", 0);
                if (messages.length != 0) {
                    for (var msgid in messages) {
                        var msg = messages[msgid];
                        msg.read = true;
                        messages[msgid] = msg;
                        showMessage(msg);
                    }
                    updateMessages(key, messages);//更新为read
                }

                setTimeout(function () {
                    $('.message').animate({scrollTop:  $(".message")[0].scrollHeight}, 300);
                },1000);
//                $('.message').animate({scrollTop: $(document).height()}, 300);

            } catch (err) {
                alert(err.message);
            }


//            console.log("更新的msg是"+JSON.stringify(messages));
//            if ($(".message")[0].scrollHeight > $(window).height()) {
//                $('.message').animate({scrollTop: $(".message")[0].scrollHeight}, 200);
//            }
        }




        function showMessage(msg) {

//            var msg = JSON.parse(data);
//            console.log("正在渲染" + JSON.stringify(msg));
            //渲染一条设置已经看过

//            console.log("---设置看了"+msg.read);
            switch (msg.type) {
                case "voice" :
                    var data = msg;
                    var lenght = "3\"";
                    data.length = lenght;
                    var localId = getVLocalId(msg.msg);
                    data.localId = localId.trim();
                    var serverId = getVServerId(msg.msg);
                    data.serverId = serverId;
                    var show;
                    //播放过就不显示
                    if (msg.played != null && msg.played == true) {
                        show = "none";
                        data.show = show;
                    }
                    if (msg.fromId == mid) {//自己发的
                        $("#mvt").tmpl(data).appendTo($(".message"));
                    } else {
                        $("#ovt").tmpl(data).appendTo($(".message"));
                    }
                    break;
                case "img":
                    var data = msg;
                    var localId = getVLocalId(msg.msg);
                    data.localId = localId.trim();
                    var serverId = getVServerId(msg.msg);
                    data.serverId = serverId;
                    if (msg.fromId == mid) {//自己发的
                        $("#mit").tmpl(data).appendTo($(".message"));
                    } else {//如果是别人发送给自己的 先去更新
                        if(msg["read"] == null||msg["read"] != true){//没看过设置图片为默认图片 然后下载图片更新localId
                            localId = "${ctx}/resources/mallimages/jz.png";
                            data.localId = localId;//重新赋值
                            var obj =  $("#oit").tmpl(data);
                            obj.appendTo($(".message"))
                            downloadImage(obj,serverId);//下载图片并且更新
                        }else {
                            $("#oit").tmpl(data).appendTo($(".message"));
                        }

                    }
                    break;
                default:
                    if (msg.fromId == mid) {
                        $("#mt").tmpl(msg).appendTo($(".message"));
                    } else {
                        $("#ot").tmpl(msg).appendTo($(".message"));
                    }

            }

            msg["read"] = true;
            $('.message').animate({scrollTop: $(".message")[0].scrollHeight }, 0);
            $(".message").css("opacity", 1);
        }

        //--------------微信发送语音相关---------------//


        //微信jssdk相关
        var jsapiParamJson = ${jsapiParam};
//        jsapiParamJson = $.parseJSON(jsapiParamJson);
        wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: jsapiParamJson.appId, // 必填，公众号的唯一标识
            timestamp: jsapiParamJson.timestamp, // 必填，生成签名的时间戳
            nonceStr: jsapiParamJson.nonceStr, // 必填，生成签名的随机串
            signature: jsapiParamJson.signature,// 必填，签名，见附录1
            jsApiList: ['startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'onVoicePlayEnd', 'uploadVoice', 'downloadVoice','chooseImage','previewImage','uploadImage','downloadImage'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        });

        var sockjs;

        function openMySocket() {
            var sockjs_url = "<c:url value='/messageHandler'/>";
            sockjs = new SockJS(sockjs_url);
            sockjs.onopen = function () {
                console.log("连接成功");
            };
            sockjs.onmessage = function (e) {
                var msg = JSON.parse(e.data);
                if (msg instanceof Array) {
                    for (var a in msg) {
                        console.log(a);
                        console.log(msg[a]);
                        if (msg[a].fromId == oid) {//是当前用户传过来的才显示
                            showMessage(msg[a]);
                        }
                        //保存即可
                        saveMsg(msg[a], msg[a].fromId);
                    }
                } else {
                    if (msg.fromId == oid) {//是当前用户传过来的才显示
                        showMessage(msg);
                    }
                    //保存即可
                    saveMsg(msg, msg.fromId);
                }
            };
            sockjs.onclose = function () {
                console.log("连接关闭2！");
            };
            sockjs.onerror = function (e) {
                console.log("发送失败！");
            };
            //离开网页前关闭
            window.onbeforeunload = function () {
                alert("--正在离线");
                sockjs.close();
            }
        }


        //一加载就去获取权限
        wx.ready(function () {

            openMySocket();


            //首先获取权限
            if (!localStorage.rainAllowRecord || localStorage.rainAllowRecord !== 'true') {
                wx.startRecord({
                    success: function () {
                        localStorage.rainAllowRecord = 'true';
                        setTimeout(function () {
                            wx.stopRecord();
                        }, 500);

                    },
                    cancel: function () {
                        alert('用户拒绝授权录音');
                    }
                });
            }

            wx.onVoicePlayEnd({
                success: function (res) {
                    var localId = res.localId; // 返回音频的本地ID 这个localId不是当初发送的那个了
                    stopWave(localId);
                }
            });

        })


        //录音相关
        var voice = {"localId": "", "serverId": ""};
        var intid;//循环替换语音图片进程
        var STARTTIME;
        var ENDTIME;
        var recordTimer;//录音延迟进程名
        //语音长按讲话
        $(".sb").on('touchstart', function (e) {
            STARTTIME = new Date();
            $(".sdiv").show();
            $(this).children("span").addClass("press");
            e.preventDefault();
            var ip = "${ctx}/resources/mallimages/v";
            var imgs = [];
            for (var i = 0; i < 7; i++) {
                imgs[i] = ip + (i + 1) + ".jpg";
            }
            var index = 1;
            intid = setInterval(function () {
                $("#simg").attr("src", imgs[index]);
                index++;
                if (index > 7) {
                    index = 0;
                }

            }, 100);
            //开始录音
            recordTimer = setTimeout(function () {
                recordVoice();
            }, 300);
        });

        //语音结束长按
        $(".sb").on('touchend', function (e) {
                ENDTIME = new Date();
                $(".sdiv").hide();
                clearInterval(intid);
                $("#simg").attr("src", "${ctx}/resources/mallimages/v1.jpg");
                $(this).children("span").removeClass("press");
                e.preventDefault();
                if (ENDTIME - STARTTIME < 300) {
                    ENDTIME = 0;
                    STARTTIME = 0;
                    //小于300ms，不录音
                    clearTimeout(recordTimer);
                } else {
                    stopRecord();//结束录音并且上传录音
                }
            }
        );
        //自己的消息点击事件
        $(".message").delegate(".my .voice", "click", function () {
            //获取本地id
            var localId = $(this).attr("local-id");
            //播放声音
            playVoice(localId);

            //开启动画
            startWave($(this), true);

        })

        //别人消息点击事件
        $(".message").delegate(".other .voice", "click", function () {
            var msgId = $(this).attr("msg-id");
            var serverId = $(this).attr("server-id");
            //下载声音
            downVoiceAndPlay(serverId, $(this));
            //移除未播放状态
            $(this).find(".nrb").css("visibility", "hidden");
            //更新状态 设置为已播放
            var friendId = $(this).attr("from-id");
            var messages = getMsgsArrayByUid(friendId);
            var msg = messages[msgId];
            msg["played"] = true;
//            msg["msg"] = localId+"+"+serverId;
//            $(this).attr("local-id",localId);//更新dom中的localId
//            alert(JSON.stringify(msg));
            messages[msgId] = msg;
            updateMessages(friendId, messages);//重新存储


        })

        //从发送的语音消息中获取本地ID
        function getVLocalId(vid) {
            var strs = vid.split("+");
            return strs[0].trim();
        }

        //从发送的语音消息中获取服务器端ID
        function getVServerId(vid) {
            var strs = vid.split("+");
            return strs[1].trim();
        }


        //录音方法封装
        function recordVoice() {
            //开始录用 需要授权
            wx.startRecord({
                success: function () {
                    localStorage.rainAllowRecord = 'true';//记录已经授权
                },
                cancel: function () {
                    alert('用户拒绝授权录音');
                }
            });
            //
        }

        //结束录音
        function stopRecord() {
            wx.stopRecord({
                success: function (res) {
                    voice.localId = res.localId;
                    uploadVoice();
                },
                fail: function (res) {
                    alert(JSON.stringify(res));
                }
            });
        }

        //上传录音 结束录音的时候调用
        function uploadVoice() {
            //调用微信的上传录音接口把本地录音先上传到微信的服务器
            //不过，微信只保留3天，而我们需要长期保存，我们需要把资源从微信服务器下载到自己的服务器
            wx.uploadVoice({
                localId: voice.localId, // 需要上传的音频的本地ID，由stopRecord接口获得
                isShowProgressTips: 1, // 默认为1，显示进度提示
                success: function (res) {
                    voice.serverId = res.serverId;
                    //发送消息 消息类型为voice  上传成功发送语音 本地ID自己播放 serverId用于下载
                    var msg = sendMessage(mid, oid, avatar, voice.localId + "+" + res.serverId, name, code, "voice");//发送声音
                    showMessage(msg);
                    saveMsg(msg, oid);//存储数据
                    //把录音在微信服务器上的id（res.serverId）发送到自己的服务器供下载。
//                    $.ajax({
//                        url: '后端处理上传录音的接口',
//                        type: 'post',
//                        data: JSON.stringify(res),
//                        dataType: "json",
//                        success: function (data) {
//                            alert('文件已经保存到七牛的服务器');//这回，我使用七牛存储
//                        },
//                        error: function (xhr, errorType, error) {
//                            console.log(error);
//                        }
//                    });
                }
            });
        }

        //播放声音
        function playVoice(localId) {
            localId = localId.trim();//去除空格
            wx.playVoice({

                localId: localId // 需要播放的音频的本地ID，由stopRecord接口获得

            });

        }

        var intIds = {};

        //播放动画 isMy是否是我这边的动画
        function startWave(obj, isMy) {
            var vImg = "${ctx}/resources/mallimages/";
            var localId = obj.attr("local-id");
            var imgs;
            if (isMy) {
                imgs = ["rv1.png?s=2", "rv2.png", "rv3.png"];
            } else {
                imgs = ["lv1.png", "lv2.png", "lv3.png"];
            }
            var index = 0;
            var intId = setInterval(function () {
                obj.find("img").attr("src", vImg + imgs[index]);
                index++;
                if (index > 2) {
                    index = 0;
                }

            }, 300);

            intIds[localId] = intId;//通过这个来停止动画

        }

        //停止动画 通过attr参数localId
        function stopWave(localId) {
            var intId = intIds[localId];
            if (intId != null) {
                clearInterval(intId);
                //设置恢复背景
                var obj = $("div[local-id = '" + localId + "']");
                if (obj.attr("from-id") == mid) {//自己发的
                    obj.find("img").attr("src", "${ctx}/resources/mallimages/rv3.png?s=2");
                } else {
                    obj.find("img").attr("src", "${ctx}/resources/mallimages/lv3.png?s=2");
                }
            }
        }

        //暂停声音
        function pauseVoice(vid) {
            wx.pauseVoice({

                localId: vid // 需要暂停的音频的本地ID，由stopRecord接口获得

            });
        }

        //停止播放
        function stopVoice(vid) {
            wx.stopVoice({

                localId: vid // 需要停止的音频的本地ID，由stopRecord接口获得

            });
        }

        //下载声音 直接播放
        function downVoiceAndPlay(serverId, obj) {
            wx.downloadVoice({

                serverId: serverId, // 需要下载的音频的服务器端ID，由uploadVoice接口获得

                isShowProgressTips: 1, // 默认为1，显示进度提示

                success: function (res) {
                    var localId = res.localId; // 返回音频的本地ID
                    //            //开启动画
                    obj.attr("local-id", localId);
                    startWave(obj, false);
                    playVoice(localId);
                }

            });

        }

        //发送图片相关**************************************************
        $(".add").click(function () {
            chooseImage();
        })


        //选择图片
        function chooseImage() {
            wx.chooseImage({

                count: 9, // 默认9

                sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有

                sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有

                success: function (res) {
                    var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                    //选中了直接上传
//                    localIds = localIds+"";
//                    var s = localIds.split(",");
                    localIds.forEach(function (v,k) {
                        uploadImage(v);//上传  上传就是发送了
                    })
                }
            });
        }


        //上传图片
        function uploadImage(localId) {
            wx.uploadImage({

                localId: localId, // 需要上传的图片的本地ID，由chooseImage接口获得

                isShowProgressTips: 1, // 默认为1，显示进度提示

                success: function (res) {
//                    var serverId = res.serverId; // 返回图片的服务器端ID
                    //发送
                    var msg = sendMessage(mid, oid, avatar, localId + "+" + res.serverId, name, code, "img");//发送图片
                    showMessage(msg);
                    saveMsg(msg, oid);//存储数据
                }

            });
        }

        //预览图片
        function previewImage() {

        }



        //下载图片
        function downloadImage(obj,serverId) {



            wx.downloadImage({

                serverId: serverId, // 需要下载的图片的服务器端ID，由uploadImage接口获得

                isShowProgressTips: 0, // 默认为1，显示进度提示

                success: function (res) {
                    var localId = res.localId; // 返回图片下载后的本地ID
                    localId = localId.trim();
                    obj.find(".mes").css("background", 'url("' + localId + '")');
                    obj.find(".mes").attr("local-id", localId);
                    obj.find(".mes").find("img").attr("src",localId);
                    obj.find(".mes").attr("msg-id");
                    var uid = obj.find(".mes").attr("from-id");
                    var msgId = obj.find(".mes").attr("msg-id");
//                    alert(uid+"="+msgId);
                    updateMsg(uid,msgId,"msg",localId+"+"+serverId);
//                    alert("革新完毕");
//                    alert(obj.find("img").attr("src"));
                }

            });
        }


    })
</script>


<!--文字模板-->
<script id="mt" type="text/x-jquery-tmpl">
    <div class="my bar">
       <div class="img">
            <img src="{{= avatar}}" alt="">
        </div>

        <div class="mes" from-id={{= fromId}}  to-id={{= toId}}>
           {{= msg}}
        </div>



    </div>

</script>

<script id="ot" type="text/x-jquery-tmpl">
    <div class="other bar">

        <div class="img">
            <img src="{{= avatar}}" alt="">
        </div>

        <div class="mes" from-id={{= fromId}}  to-id={{= toId}}>
           {{= msg}}
        </div>
</div>


</script>

<!--语音模板-->
<script id="mvt" type="text/x-jquery-tmpl">
    <div class="my bar">
        <div class="img">
        <img src="{{= avatar}}" alt="">
        </div>
        <div class="mes voice" from-id={{= fromId}}  to-id={{= toId}} local-id={{= localId}} server-id={{= serverId}} msg-id={{= msgId}}>
        <span>{{= length}}</span>
            <img src="${ctx}/resources/mallimages/rv3.png?s=2" alt="">
        </div>
        </div>

</script>

<script id="ovt" type="text/x-jquery-tmpl">
<div class="other bar">
    <div class="img">
         <img src="{{= avatar}}" alt="">
    </div>

     <div class="mes voice" from-id={{= fromId}}  to-id={{= toId}} local-id={{= localId}} server-id={{= serverId}} msg-id={{= msgId}} >

        <img src="{{= avatar}}" alt="">

        <span>{{= length}}</span>

        <span class="nrb {{= show}}"></span>

    </div>
</div>

</script>

<!--图片模板-->
<script id="mit" type="text/x-jquery-tmpl">
    <div class="my bar">
        <div class="img">
        <img src="{{= avatar}}" alt="">
        </div>
        <%--<div style="background: url('${ctx}/resources/mallimages/jz.png') no-repeat" class="mes images" from-id={{= fromId}}  to-id={{= toId}}>--%>
        <div style="background: url('{{= localId}}') no-repeat" class="mes images" from-id={{= fromId}}  to-id={{= toId}} local-id={{= localId}} server-id={{= serverId}} msg-id={{= msgId}}>
        <%--<img style="width: 100%" src="${ctx}/resources/mallimages/jz.png" alt="">--%>
        <img style="width: 100%" src="{{= localId}}" alt="">
        </div>


    </div>
</script>

<script id="oit" type="text/x-jquery-tmpl">
<div class="other bar">
    <div class="img">
        <img src="{{= avatar}}" alt="">
    </div>
        <div style="background: url('{{= localId}}') no-repeat" class="mes images" from-id={{= fromId}}  to-id={{= toId}} local-id={{= localId}} server-id={{= serverId}} msg-id={{= msgId}}>
        <%--<img style="width: 100%" src="${ctx}/resources/mallimages/jz.png" alt="">--%>
        <img style="width: 100%" src="{{= localId}}" alt="">
</div>
</script>

</body>
</html>